package com.jacoblyu.factoryrunner.ui.views

import androidx.compose.foundation.background
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.ArrowBack
import androidx.compose.material.icons.filled.ArrowForward
import androidx.compose.material.icons.filled.Camera
import androidx.compose.material.icons.filled.Home
import androidx.compose.material3.*
import androidx.compose.runtime.*
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.platform.LocalConfiguration
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.navigation.NavController
import androidx.navigation.compose.rememberNavController
import com.jacoblyu.factoryrunner.data.TestResultManager
import com.jacoblyu.factoryrunner.ui.theme.*

@Composable
fun RearCameraTestView(navController: NavController) {
    // 获取Context用于TestResultManager
    val context = LocalContext.current
    val testResultManager = remember { TestResultManager(context) }
    // 根据屏幕尺寸调整字体和间距
    val screenWidth = LocalConfiguration.current.screenWidthDp
    val screenHeight = LocalConfiguration.current.screenHeightDp
    
    // 根据屏幕尺寸调整字体大小
    val titleFontSize = if (screenWidth >= 1920) 48.sp else 32.sp
    val contentFontSize = if (screenWidth >= 1920) 36.sp else 24.sp
    val buttonFontSize = if (screenWidth >= 1920) 28.sp else 18.sp
    
    // 根据屏幕尺寸调整间距
    val spacing = if (screenWidth >= 1920) 32.dp else 24.dp
    val buttonHeight = if (screenWidth >= 1920) 80.dp else 60.dp
    val buttonWidth = if (screenWidth >= 1920) 200.dp else 150.dp
    
    // 测试状态
    var cameraOn by remember { mutableStateOf(false) }
    var flashOn by remember { mutableStateOf(false) }
    var resolution by remember { mutableStateOf("1920x1080") }
    var focusMode by remember { mutableStateOf("自动对焦") }
    // 从TestResultManager加载测试结果
    var testResult by remember { mutableStateOf(testResultManager.getTestResult("高拍摄像头测试")) }
    
    Box(
        modifier = Modifier
            .fillMaxSize()
            .background(MaterialTheme.colorScheme.background)
    ) {
        // 标题栏
        Row(
            modifier = Modifier
                .fillMaxWidth()
                .padding(spacing),
            horizontalArrangement = Arrangement.SpaceBetween,
            verticalAlignment = Alignment.CenterVertically
        ) {
            // Home按钮
            IconButton(
                onClick = { navController.navigate("home") }
            ) {
                Icon(
                    imageVector = Icons.Filled.ArrowBack,
                    contentDescription = "上一步",
                    tint = MaterialTheme.colorScheme.primary,
                    modifier = Modifier.size(if (screenWidth >= 1920) 48.dp else 36.dp)
                )
            }
            
            // 标题
            Text(
                text = "后置摄像头测试",
                fontSize = titleFontSize,
                fontWeight = FontWeight.Bold,
                color = MaterialTheme.colorScheme.primary
            )
            
            // Home按钮
            IconButton(
                onClick = { navController.navigate("home") }
            ) {
                Icon(
                    imageVector = Icons.Filled.Home,
                    contentDescription = "返回主页",
                    tint = MaterialTheme.colorScheme.primary,
                    modifier = Modifier.size(if (screenWidth >= 1920) 48.dp else 36.dp)
                )
            }
            
            // 下一步按钮
            IconButton(
                onClick = { navController.navigate("tfcard_test") }
            ) {
                Icon(
                    imageVector = Icons.Filled.ArrowForward,
                    contentDescription = "下一步",
                    tint = MaterialTheme.colorScheme.primary,
                    modifier = Modifier.size(if (screenWidth >= 1920) 48.dp else 36.dp)
                )
            }
        }
        
        // 内容区域
        Column(
            modifier = Modifier
                .fillMaxSize()
                .padding(spacing),
            horizontalAlignment = Alignment.CenterHorizontally,
            verticalArrangement = Arrangement.Center
        ) {
            // 后置摄像头测试内容
            Card(
                modifier = Modifier
                    .fillMaxWidth(0.8f)
                    .height((screenHeight * 0.5f).dp),
                shape = RoundedCornerShape(16.dp),
                colors = CardDefaults.cardColors(
                    containerColor = MaterialTheme.colorScheme.surface
                ),
                elevation = CardDefaults.cardElevation(
                    defaultElevation = 8.dp
                )
            ) {
                Column(
                    modifier = Modifier
                        .fillMaxSize()
                        .padding(spacing),
                    horizontalAlignment = Alignment.CenterHorizontally,
                    verticalArrangement = Arrangement.SpaceEvenly
                ) {
                    // 摄像头图标
                    Icon(
                        imageVector = Icons.Filled.Camera,
                        contentDescription = "摄像头图标",
                        tint = if (cameraOn) MaterialTheme.colorScheme.primary 
                              else MaterialTheme.colorScheme.onSurface.copy(alpha = 0.6f),
                        modifier = Modifier.size(if (screenWidth >= 1920) 120.dp else 80.dp)
                    )
                    
                    // 状态文本
                    Text(
                        text = if (cameraOn) "后置摄像头已开启" else "后置摄像头已关闭",
                        fontSize = contentFontSize,
                        fontWeight = FontWeight.Bold,
                        color = if (cameraOn) Color.Green 
                               else MaterialTheme.colorScheme.onSurface,
                        textAlign = TextAlign.Center
                    )
                    
                    // 分辨率选择
                    Row(
                        horizontalArrangement = Arrangement.Center,
                        verticalAlignment = Alignment.CenterVertically
                    ) {
                        Text(
                            text = "分辨率:",
                            fontSize = contentFontSize,
                            fontWeight = FontWeight.Medium,
                            color = MaterialTheme.colorScheme.onSurface
                        )
                        
                        Spacer(modifier = Modifier.width(spacing))
                        
                        // 分辨率选择按钮
                        Row(
                            horizontalArrangement = Arrangement.spacedBy(spacing / 2)
                        ) {
                            val resolutions = listOf("1920x1080", "3840x2160")
                            resolutions.forEach { res ->
                                Button(
                                    onClick = { resolution = res },
                                    modifier = Modifier.height(buttonHeight * 0.7f),
                                    colors = ButtonDefaults.buttonColors(
                                        containerColor = if (resolution == res) MaterialTheme.colorScheme.primary 
                                                       else MaterialTheme.colorScheme.surface
                                    )
                                ) {
                                    Text(
                                        text = res,
                                        fontSize = buttonFontSize * 0.8f,
                                        color = if (resolution == res) MaterialTheme.colorScheme.onPrimary 
                                               else MaterialTheme.colorScheme.onSurface
                                    )
                                }
                            }
                        }
                    }
                    
                    // 闪光灯开关
                    Row(
                        horizontalArrangement = Arrangement.Center,
                        verticalAlignment = Alignment.CenterVertically
                    ) {
                        Text(
                            text = "闪光灯:",
                            fontSize = contentFontSize,
                            fontWeight = FontWeight.Medium,
                            color = MaterialTheme.colorScheme.onSurface
                        )
                        
                        Spacer(modifier = Modifier.width(spacing))
                        
                        Switch(
                            checked = flashOn,
                            onCheckedChange = { flashOn = it },
                            enabled = cameraOn
                        )
                    }
                    
                    // 对焦模式选择
                    Row(
                        horizontalArrangement = Arrangement.Center,
                        verticalAlignment = Alignment.CenterVertically
                    ) {
                        Text(
                            text = "对焦模式:",
                            fontSize = contentFontSize,
                            fontWeight = FontWeight.Medium,
                            color = MaterialTheme.colorScheme.onSurface
                        )
                        
                        Spacer(modifier = Modifier.width(spacing))
                        
                        // 对焦模式选择按钮
                        Row(
                            horizontalArrangement = Arrangement.spacedBy(spacing / 2)
                        ) {
                            val focusModes = listOf("自动对焦", "手动对焦")
                            focusModes.forEach { mode ->
                                Button(
                                    onClick = { focusMode = mode },
                                    modifier = Modifier.height(buttonHeight * 0.7f),
                                    colors = ButtonDefaults.buttonColors(
                                        containerColor = if (focusMode == mode) MaterialTheme.colorScheme.primary 
                                                       else MaterialTheme.colorScheme.surface
                                    )
                                ) {
                                    Text(
                                        text = mode,
                                        fontSize = buttonFontSize * 0.8f,
                                        color = if (focusMode == mode) MaterialTheme.colorScheme.onPrimary 
                                               else MaterialTheme.colorScheme.onSurface
                                    )
                                }
                            }
                        }
                    }
                    
                    Spacer(modifier = Modifier.height(spacing))
                    
                    // 开启/关闭摄像头按钮
                    Button(
                        onClick = { 
                            cameraOn = !cameraOn
                            testResult = if (cameraOn) "测试中..." else "已测试"
                        },
                        modifier = Modifier
                            .width(buttonWidth * 1.5f)
                            .height(buttonHeight),
                        colors = ButtonDefaults.buttonColors(
                            containerColor = if (cameraOn) MaterialTheme.colorScheme.secondary 
                                           else MaterialTheme.colorScheme.primary
                        )
                    ) {
                        Text(
                            text = if (cameraOn) "关闭摄像头" else "开启摄像头",
                            fontSize = buttonFontSize,
                            color = MaterialTheme.colorScheme.onPrimary
                        )
                    }
                }
            }
            
            Spacer(modifier = Modifier.height(spacing))
            
            // 按钮区域
            Row(
                horizontalArrangement = Arrangement.spacedBy(spacing),
                verticalAlignment = Alignment.CenterVertically
            ) {
                // 不通过按钮
                Button(
                    onClick = { 
                        // 保存测试结果到TestResultManager
                        testResultManager.saveTestResult("高拍摄像头测试", "失败")
                        testResult = "失败"
                        // 导航到下一个测试页面
                        navController.navigate("tfcard_test?result=失败&test=高拍摄像头测试")
                    },
                    modifier = Modifier
                        .width(buttonWidth)
                        .height(buttonHeight),
                    colors = ButtonDefaults.buttonColors(
                        containerColor = MaterialTheme.colorScheme.error
                    )
                ) {
                    Text(
                        text = "不通过",
                        fontSize = buttonFontSize,
                        color = MaterialTheme.colorScheme.onError
                    )
                }
                
                // 通过按钮
                Button(
                    onClick = { 
                        // 保存测试结果到TestResultManager
                        testResultManager.saveTestResult("高拍摄像头测试", "通过")
                        testResult = "通过"
                        // 导航到下一个测试页面
                        navController.navigate("tfcard_test?result=通过&test=高拍摄像头测试")
                    },
                    modifier = Modifier
                        .width(buttonWidth)
                        .height(buttonHeight),
                    colors = ButtonDefaults.buttonColors(
                        containerColor = MaterialTheme.colorScheme.primary
                    )
                ) {
                    Text(
                        text = "通过",
                        fontSize = buttonFontSize,
                        color = MaterialTheme.colorScheme.onPrimary
                    )
                }
            }
        }
    }
}

@Preview(showBackground = true)
@Composable
fun RearCameraTestPreview() {
    FactoryrunnerTheme {
        RearCameraTestView(rememberNavController())
    }
}

@Preview(showBackground = true, widthDp = 1920, heightDp = 1200)
@Composable
fun RearCameraTestLargePreview() {
    FactoryrunnerTheme {
        RearCameraTestView(rememberNavController())
    }
}